<?php

/**
 * 获得随机字符串
 * @param   Number  $len    需要的长度
 * @param   Bool    $special    是否需要特殊符号
 * @return  String  返回随机字符串
 */
function build_ranstr($len = 8, $special = false)
{
    $chars = array(
        "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
        "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
        "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
        "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
        "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
        "3", "4", "5", "6", "7", "8", "9"
    );

    if ($special) {
        $chars = array_merge($chars, array(
            "!", "@", "#", "$", "?", "|", "{", "/", ":", ";",
            "%", "^", "&", "*", "(", ")", "-", "_", "[", "]",
            "}", "<", ">", "~", "+", "=", ",", "."
        ));
    }

    $charsLen = count($chars) - 1;
    shuffle($chars);                            //打乱数组顺序
    $str = '';
    for ($i = 0; $i < $len; $i++) {
        $str .= $chars[mt_rand(0, $charsLen)];    //随机取出一位
    }
    return $str;
}

// 定义一个图片的宽高
$width = 80;
$height = 34;

// 创建画布
$img=imagecreatetruecolor($width,$height);

 //设置背景颜色,颜色必须使用rgb格式
 $bgcolor=imagecolorallocate($img,238,238,238);//#eeeeee

 //设置文字颜色
 $textcolor=imagecolorallocate($img,255,0,0);//#ff0000

 // 设置背景色
 imagefilledrectangle($img,0,0,$width,$height,$bgcolor);

 $code1 = build_ranstr(1);
 $code2 = build_ranstr(1);
 $code3 = build_ranstr(1);
 $code4 = build_ranstr(1);

//  如果字体没出现 说明路径或者文件有问题 macos 写相对路径或绝对路径 win 如果php < 7 写相对路径 如果 php > 7 写绝对路径 
 $font = 'E:/phpstudy/project/learnPHP/0510/admin/static/font/OpenSans-Light.ttf';
 imagettftext($img,16,mt_rand(-30,30),5,26,$textcolor,$font,$code1);
 imagettftext($img,16,mt_rand(-30,30),20,26,$textcolor,$font,$code2);
 imagettftext($img,16,mt_rand(-30,30),40,26,$textcolor,$font,$code3);
 imagettftext($img,16,mt_rand(-30,30),60,26,$textcolor,$font,$code4);

// 绘制一些点状像素
for($i=0;$i<=50;$i++){
    imagesetpixel($img,mt_rand(0,$width),mt_rand(0,$height),imagecolorallocate($img,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255)));
}

//绘制一些线像素
for($i=0;$i<=5;$i++){
    imageline($img,mt_rand(0,$width),mt_rand(0,$height),mt_rand(0,$width),mt_rand(0,$height),imagecolorallocate($img,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255)));
}

// 开启session会话 需要使用session必须要开启会话 如果没开，无法保存session
session_start();

$imgcode = $code1 . $code2 . $code3 . $code4;

$_SESSION['imgcode'] = $imgcode;

// 设置该文件输出格式
header('Content-Type:image/png');
// 输出图片
imagepng($img);